package com.fy56.platform.logistics.restful.api.utils;

import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fy56.platform.logistics.utils.HttpClientUtils;

/***
 * 微信服务通知工具类
 *
 */
public class WeChatServiceNoticeUtil {

    /**
      * WeChatServiceNoticeUtil 私有单例对象。
      */
    private static WeChatServiceNoticeUtil weChatServiceNoticeUtil = null;
    /**
     * 用于解析发送模板消息时，返回的错误信息
     */
    private static Map<String, String> resultMsg = null;
    // 获取小程序 access_token 地址URL
    private static String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?";
    // 发送模版通知地址URL
    private static String SEND_TEMPLATE_NOTICE_URL = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=";

    private  WeChatServiceNoticeUtil(){ }

    /***
     *  获取 WeChatServiceNoticeUtil对象
     * @return
     */
    public static  WeChatServiceNoticeUtil getInstance(){
        if(weChatServiceNoticeUtil == null){
            weChatServiceNoticeUtil = new WeChatServiceNoticeUtil();
            resultMsg = new HashMap<String, String>();
            resultMsg.put("40037","template_id不正确");
            resultMsg.put("41028","form_id不正确，或者过期");
            resultMsg.put("41029","form_id已被使用");
            resultMsg.put("41030","page不正确");
            resultMsg.put("45009","接口调用超过限额（目前默认每个帐号日调用限额为100万）");
        }
        return weChatServiceNoticeUtil;
    }

    /***
     *  发送小程序服务通知
     *
     * @param accessToken
     * @param touser
     * @param template_id
     * @param page
     * @param formid
     * @param arrayKeywords
     * @return
     * @throws Exception
     */
    public  String sendServiceNotice(String accessToken, String touser, String template_id, String formid, String page, String[] arrayKeywords)throws Exception{
        String result = "";
        // 获取发送模版通知 JSON数据
        String params = weChatServiceNoticeUtil.getTemplateMessageJson(touser, template_id, formid, page, arrayKeywords);
        result = HttpClientUtils.postParameters(SEND_TEMPLATE_NOTICE_URL + accessToken, params);
        return result;
    }

    /**
     * 获取小程序AccessToken信息
     *
     * @param appId         wx73c4afcb6ead88fd
     * @param appSecret  	3c5f81cfd2b67d3cb081917aae83e5f5
     * @return
     * @throws Exception
     */
    public String getWeChatAccessToken(String appId, String appSecret)throws Exception{
        String url = ACCESS_TOKEN_URL + "grant_type=client_credential&appid=" + appId + "&secret=" + appSecret;
        return HttpClientUtils.get(url, null);
    }

    /**
     * 将TemplateMessage数据对象转换为JSON串数据
     *
     * @param touser
     * @param templateId
     * @param page
     * @param formId
     * @param arrayKeywords
     * @return
     */
    public String getTemplateMessageJson(String touser, String templateId, String formId, String page, String[] arrayKeywords){
        // 获取服务通知模版显示信息
        Map<String, TemplateData> mapKeywords = weChatServiceNoticeUtil.getTemplateDateMap(arrayKeywords);
        TemplateMessage templateMessage = new TemplateMessage();
        templateMessage.setTouser(touser);
        templateMessage.setTemplate_id(templateId);
        templateMessage.setForm_id(formId);
        templateMessage.setPage(page);
        templateMessage.setData(mapKeywords);
        templateMessage.setEmphasis_keyword("");
        return JSONObject.toJSONString(templateMessage);
    }

    /**
     * 拼装模版信息数据
     *
     * @param keywords
     * @return
     */
    public Map<String, TemplateData> getTemplateDateMap(String[] keywords ){
        Map<String, TemplateData> mapKeywords = new HashMap<String,TemplateData>();
        if(keywords != null && keywords.length > 0){
            for(int i=0; i< keywords.length; i++){
                mapKeywords.put("keyword" + (i+1) , new TemplateData(keywords[i]));
            }
        }
        return  mapKeywords;
    }


    /**
     * 获取发送模板通知返回的信息
     *
     * @param jsonValue
     * @return
     */
    public String getJSONResultAnalysis(String jsonValue){
        String result = "";
        if(jsonValue != null && jsonValue.length()>0){
            Map<String, Object> jsonMap = JSON.parseObject(jsonValue);
            if(!jsonMap.isEmpty()){
                String mapResult = resultMsg.get(jsonMap.get("errcode")+"");
                if(mapResult != null && mapResult.length()>0){
                    result = mapResult;
                }else {
                    result = jsonValue;
                }
            }
        }
        return result;
    }

    /**
      * 模板消息类
      */
    class TemplateMessage {
    
        //接收者（用户）的 openid
        private String touser;
        //所需下发的模板消息的id
        private String template_id;
        //点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
        private String page;
        //表单提交场景下，为 submit 事件带上的 formId；支付场景下，为本次支付的 prepay_id
        private String form_id;
        //模板内容，不填则下发空模板
        private Map<String,TemplateData> data;
        //模板需要放大的关键词，不填则默认无放大
        private String emphasis_keyword;

        public String getTouser() {
            return touser;
        }

        public void setTouser(String touser) {
            this.touser = touser;
        }

        public String getTemplate_id() {
            return template_id;
        }

        public void setTemplate_id(String template_id) {
            this.template_id = template_id;
        }

        public String getPage() {
            return page;
        }

        public void setPage(String page) {
            this.page = page;
        }

        public String getForm_id() {
            return form_id;
        }

        public void setForm_id(String form_id) {
            this.form_id = form_id;
        }

        public Map<String, TemplateData> getData() {
            return data;
        }

        public void setData(Map<String, TemplateData> data) {
            this.data = data;
        }

        public String getEmphasis_keyword() {
            return emphasis_keyword;
        }

        public void setEmphasis_keyword(String emphasis_keyword) {
            this.emphasis_keyword = emphasis_keyword;
        }
    }

    /**
     * 模板中 显示数据类
     */
    class TemplateData {
        private String value;

        public TemplateData() { }
        public TemplateData(String value) {
            this.value = value;
        }

        public String getValue() {
            return value;
        }
        public void setValue(String value) {
            this.value = value;
        }
    }

    public static void main(String[] args)throws Exception{
            // 1 获取accessToken
            String appId = "wx73c4afcb6ead88fd";
            String appSecret = "3c5f81cfd2b67d3cb081917aae83e5f5";
            Map<String, Object> tokenMap = JSON.parseObject( WeChatServiceNoticeUtil.getInstance().getWeChatAccessToken(appId, appSecret));
            String accessToken = (tokenMap != null && !tokenMap.isEmpty()) ? tokenMap.get("access_token").toString() : "";

            // 2 发送模板通知
            String touser = "olqdc5QyOiinXhgW_njf_GYekHjA";
            String templateId = "mk8ZC0U7f6egJSALisOaccmQjNd4CJXZ9Wa2vC1MmJg";
            String formid = "1541386001740";
            String result = WeChatServiceNoticeUtil.getInstance().sendServiceNotice(accessToken, touser, templateId, formid, "", new String[]{"15004526246", "哈尔滨", "济南，货物到达请查收。"});
            System.out.println("ResultContent: " + result);
    }

}
